<?php 
declare(strict_types=1);

namespace App\Service;

use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use App\Constants\ErrorCode;
use App\Utils\ServerUtil;
use App\Dao\AdminDao;
use App\Utils\ApiUtils;
use App\Lib\JwtToken;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Hyperf\HttpMessage\Cookie\Cookie;

class LoginService
 { 

    /**
     * @Inject 
     * @var AdminDao
     */
    protected $dao;

    //验证码
    public function verify()
    {
   
        // 创建4位的字符串验证码
        $phraseBuilder = new PhraseBuilder(4, '0123456789');

        //创建验证码图片
        $builder = new CaptchaBuilder(null, $phraseBuilder);
        $builder->build(150, 40);
        $content = $builder->get();
        //把验证码存cookie
        $cookie = new Cookie('phrase_code', $builder->getPhrase());
        return ['cookie'=>$cookie,'content'=>$content];
    }

    //登录接口
    public function login($param,$cookie_code)
    {
        $name = $param['name'];
        $password = $param['password'];
        $code = $param['code'];
        $cookie = new Cookie('phrase_code',  '');
        if(empty($code) || $cookie_code != $code){
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'验证码不对');
        }
        $where[] = ['name','=' ,$name];
        $where[] = ['is_del','=' ,1];
        $info = $this->dao->searchByWhereFirst($where);
        if (empty($info)) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS,'用户名错误');
            
        } else {
            if($info->status != 1){
                throw new BusinessException(ErrorCode::ERR_BUESSUS,'该账号不能登录');
            }
            if (ApiUtils::decryption($password,$info->password)) {
                $map['last_login_time'] = time();
                $where1[] = ['is_del','=' ,$info->id];
                $this->dao->update($where1,$map);
                $token = JwtToken::authorizations($info->id, $info->name);
                $data['user_id'] = $info->id;
                $data['name'] = $info->name;
                $data['token'] = $token['token'];
                $data['refresh_token'] = $token['refresh_token'];
                $data['last_login_time'] = $map['last_login_time'];
                return $data;
            } else {
                throw new BusinessException(ErrorCode::ERR_BUESSUS,'密码错误');
               
            }
        }
    }

    //刷新token
    public function refreshToken($header)
    {
        return JwtToken::refreshToken($header[0]??'');

    }
    

 }